package com.mmall.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.mmall.beans.PageQuery;
import com.mmall.beans.PageResult;
import com.mmall.dao.SysRoleAclMapper;
import com.mmall.dao.SysRoleMapper;
import com.mmall.dao.SysRoleUserMapper;
import com.mmall.dto.DeptUserDto;
import com.mmall.exception.ParamException;
import com.mmall.model.SysDept;
import com.mmall.model.SysRole;
import com.mmall.model.SysUser;
import com.mmall.param.RoleParam;
import com.mmall.util.BeanValidator;
import com.mmall.util.DateUtil;
import com.mmall.util.UUIDUtil;

@Service
public class SysRoleService {

    @Resource
    private SysRoleMapper sysRoleMapper;
    @Resource
    private SysRoleUserMapper sysRoleUserMapper;
    @Resource
    private SysRoleAclMapper sysRoleAclMapper;
    @Resource
    private SysLogService sysLogService;
    @Resource
    private SysRoleUserService sysRoleUserService;
    @Resource
    private SysDeptService sysDeptService;

    public PageResult<SysRole> getPage(PageQuery page,SysRole sysRole) {
        BeanValidator.check(page);
        int count = sysRoleMapper.getAllByPage(sysRole).size();
        if (count > 0) {
            List<SysRole> list = sysRoleMapper.getPage(page,sysRole);
            return PageResult.<SysRole>builder().total(count).data(list).build();
        }
        return PageResult.<SysRole>builder().build();
    }
    
    public void save(RoleParam param) {
        BeanValidator.check(param);
        if (checkExist(param.getName(), param.getId())) {
            throw new ParamException("角色名称已经存在");
        }
        SysRole role = SysRole.builder().id(UUIDUtil.getUUID()).name(param.getName()).status(param.getStatus()).type(param.getType())
                .remark(param.getRemark()).build();
        role.setOperator("Admin");
        role.setOperateIp("127.0.0.1");
        role.setOperateTime(DateUtil.currentDateOfDate());
        sysRoleMapper.insertSelective(role);
        sysLogService.saveRoleLog(null, role);
    }

    public void update(RoleParam param) {
        BeanValidator.check(param);
        if (checkExist(param.getName(), param.getId())) {
            throw new ParamException("角色名称已经存在");
        }
        SysRole before = sysRoleMapper.selectByPrimaryKey(param.getId());
        Preconditions.checkNotNull(before, "待更新的角色不存在");

        SysRole after = SysRole.builder().id(param.getId()).name(param.getName()).status(param.getStatus()).type(param.getType())
                .remark(param.getRemark()).build();
        after.setOperator("Admin");
        after.setOperateIp("127.0.0.1");
        after.setOperateTime(DateUtil.str2Date(DateUtil.currentDate()));
        sysRoleMapper.updateByPrimaryKeySelective(after);
        sysLogService.saveRoleLog(before, after);
    }

    private boolean checkExist(String name, String id) {
        return sysRoleMapper.countByName(name, id) > 0;
    }
    
    public boolean delete(String roleId) {
    	SysRole role = sysRoleMapper.selectByPrimaryKey(roleId);
        Preconditions.checkNotNull(role, "待删除的角色不存在，无法删除");
        /*if(sysRoleMapper.countByRoleId(role.getId()) > 0) {
            throw new ParamException("当前角色下面有用户，无法删除");
        }*/
        return sysRoleMapper.deleteByPrimaryKey(roleId) > 0;
    }

    public SysRole selectByPrimaryKey(String keyword) {
        return sysRoleMapper.selectByPrimaryKey(keyword);
    }
    
    public List<SysRole> getAllRole() {
        return sysRoleMapper.getAllRole();
    }
    
    public Map<String, DeptUserDto> roleUserTree(String roleId){
    	List<SysUser> sysUserList = sysRoleUserService.getListByRoleId(roleId);
    	Map<String, DeptUserDto> userDeptMap = new HashMap<String, DeptUserDto>();
    	List<SysUser> userList = null;
    	DeptUserDto dto = null;
    	for (SysUser sysUser : sysUserList) {
    		if(userDeptMap.isEmpty() || null == userDeptMap.get(sysUser.getDeptId())){
    			SysDept dept = sysDeptService.getDeptById(sysUser.getDeptId());
    			dto = DeptUserDto.adapt(dept);
    			userList = Lists.newArrayList();
    		}
    		userList.add(sysUser);
    		dto.setUserList(userList);
    		//如果机构下只有一个用户则直接添加
    		if(null == userDeptMap.get(sysUser.getDeptId())){
    			userDeptMap.put(sysUser.getDeptId(), dto);
    		}else{
    			//如果一个机构下有多个用户，避免数据重复则先清楚机构与用户关系，保留最新一个关系记录
    			userDeptMap.remove(sysUser.getDeptId());
    			userDeptMap.put(sysUser.getDeptId(), dto);
    		}
    	}
    	return userDeptMap;
    }
    
}
